<template>
  <div class="audio-recorder">
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <audio v-if="audioUrl" :src="audioUrl" controls></audio>
    <p v-if="statusMessage">{{ statusMessage }}</p>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import axios from 'axios';

const isRecording = ref(false);
const mediaRecorder = ref(null);
const audioChunks = ref([]);
const audioUrl = ref(null);
const statusMessage = ref('');

const startRecording = async () => {
  try {
    statusMessage.value = '正在请求麦克风权限...';
    const stream = await navigator.mediaDevices.getUserMedia({audio: true});

    mediaRecorder.value = new MediaRecorder(stream);
    audioChunks.value = [];

    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        audioChunks.value.push(event.data);
      }
    };

    mediaRecorder.value.onstop = () => {
      const audioBlob = new Blob(audioChunks.value, {type: 'audio/wav'});
      audioUrl.value = URL.createObjectURL(audioBlob);
      sendRecordingToBackend(audioBlob);
    };

    mediaRecorder.value.start(100); // 每100ms收集一次数据
    isRecording.value = true;
    statusMessage.value = '正在录音...';
  } catch (error) {
    console.error('录音错误:', error);
    statusMessage.value = `录音错误: ${error.message}`;
  }
};

const stopRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.stop();
    mediaRecorder.value.stream.getTracks().forEach(track => track.stop());
    isRecording.value = false;
    statusMessage.value = '录音已停止，正在上传...';
  }
};

const sendRecordingToBackend = async (audioBlob) => {
  try {
    const formData = new FormData();
    formData.append('audio', audioBlob, 'recording.wav');

    const response = await axios.post('http://your-django-backend/api/recordings/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    statusMessage.value = '录音上传成功!';
    console.log('上传成功:', response.data);
  } catch (error) {
    console.error('上传失败:', error);
    statusMessage.value = `上传失败: ${error.message}`;
  }
};
</script>

<style scoped>
.audio-recorder {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  margin-right: 10px;
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

audio {
  margin-top: 20px;
  display: block;
}
</style>